# coding: utf-8
"""Pylons application test package

This package assumes the Pylons environment is already loaded, such as
when this script is imported from the `nosetests --with-pylons=test.ini`
command.

This module initializes the application via ``websetup`` (`paster
setup-app`) and provides the base testing objects.
"""
from unittest import TestCase

from paste.deploy import loadapp
from paste.script.appinstall import SetupCommand
from pylons import url
from routes.util import URLGenerator
from webtest import TestApp

import pylons.test

from papyrus.websetup import make_admin
from papyrus import model
from papyrus.model import meta

__all__ = ['environ', 'url', 'TestController', 'meta', 'model']

# Invoke websetup with the current config file
SetupCommand('setup-app').run([pylons.test.pylonsapp.config['__file__']])

environ = {}


class TestController(TestCase):

    def __init__(self, *args, **kwargs):
        wsgiapp = pylons.test.pylonsapp
        config = wsgiapp.config
        self.app = TestApp(wsgiapp)
        url._push_object(URLGenerator(config['routes.map'], environ))
        TestCase.__init__(self, *args, **kwargs)

    def setUp(self):
        """Called before each test."""
        meta.metadata.create_all(bind=meta.engine)

        # Make an admin
        user = make_admin(u"name", u"émail", u"password")
        meta.Session.add(user)

        # Make an article
        article = model.Article()
        article.author = user
        article.title = u"Some test title"
        article.body = u"""====
Test
====

This is some dummy text example.
"""
        meta.Session.commit()

        self.headers = {
            "Authorization": "Basic w6ltYWlsOnBhc3N3b3Jk",
        }

    def tearDown(self):
        """Called after each test."""
        meta.metadata.drop_all(bind=meta.engine)


class TestModel(TestController):
    """Should be inherited by SQLAlchemy unit tests"""

    def tearDown(self):
        """Called after each test method."""
        # This doesn't have to be set in the TestController as
        # meta.Session.remove() is already called in the try/finaly statement
        # in lib/base.py:BaseController.__call__ method.
        meta.Session.remove()
